<template>
  <view class="emergency_box">
    <view class="app-title ac">
      <view class="fl" @click="back">
        <image class="back" src="/static/img/back.png"></image>
      </view>
      {{ "创建临时工单" }}
    </view>

    <!-- <view class="top-bg" v-if="!param"></view> -->
    <view style="height: 140upx"></view>
    <view class="emergency_body_box">
      <view class="body_box_content">
        <scroll-view scroll-y="true" class="scroll-Y">
          <view class="list-area">
            <view class="list-item-title">基本信息</view>
            <u-form :model="listOrderData" ref="uform" :error-type="['toast']">
              <view class="rowClass">
                <u-form-item prop="major">
                  <u-cell-item
                    required
                    :border-bottom="false"
                    title="专业"
                    :value="
                      listOrderData.major == ''
                        ? '请选择'
                        : returChName(listOrderData.major, workProfession)
                    "
                    @click="
                      selece_type = 'major';
                      show_picker = true;
                      columns = workProfession;
                      label_name = 'value';
                      value_name = 'code';
                    "
                  ></u-cell-item>
                </u-form-item>
                <u-form-item prop="woLineName">
                  <u-cell-item
                    required
                    title="线路"
                    :border-bottom="false"
                    :value="
                      listOrderData.woLineName == ''
                        ? '请选择'
                        : listOrderData.woLineName
                    "
                    @click="
                      selece_type = 'line';
                      show_picker = true;
                      columns = lineTree;
                      label_name = 'name';
                      value_name = 'idK';
                    "
                  ></u-cell-item>
                </u-form-item>
              </view>
              <u-form-item prop="managementOrgName">
                <u-cell-item
                  required
                  :border-bottom="false"
                  title="机构:"
                  :value="
                    listOrderData.managementOrgName == ''
                      ? '请选择'
                      : listOrderData.managementOrgName
                  "
                  @click="showORG()"
                ></u-cell-item>
              </u-form-item>
              <u-form-item prop="locationName">
                <u-cell-item
                  required
                  title="所在地点"
                  :border-bottom="false"
                  :value="
                    listOrderData.locationName == '' ||
                    listOrderData.locationName == 'null'
                      ? '请选择'
                      : listOrderData.locationName
                  "
                  @click="show_station = true"
                ></u-cell-item>
              </u-form-item>
              <u-form-item prop="woLeaderName">
                <u-cell-item
                  title="执行人"
                  required
                  :border-bottom="false"
                  :value="
                    listOrderData.woLeaderName == ''
                      ? '请选择'
                      : listOrderData.woLeaderName
                  "
                  @click="show_people = true"
                  :arrow="false"
                >
                  <u-icon slot="right-icon" name="account"></u-icon>
                </u-cell-item>
              </u-form-item>
              <u-form-item prop="taskName">
                <u-cell-item
                  title="作业任务:"
                  required
                  :border-bottom="false"
                  :value="
                    !pmsWoDetailed[0].taskName
                      ? '请选择'
                      : pmsWoDetailed[0].taskName
                  "
                  @click="
                    selece_type = 'taskName';
                    columns = taskOptions;
                    label_name = 'value';
                    value_name = 'code';
                    show_picker = true;
                  "
                ></u-cell-item>
              </u-form-item>
              <u-form-item>
                <u-cell-item
                  :border-bottom="false"
                  title="施工区域"
                  :value="
                    listOrderData.constructArea == ''
                      ? '请选择'
                      : listOrderData.constructArea
                  "
                  @click="show_Area = true"
                ></u-cell-item>
              </u-form-item>
              <u-form-item>
                <u-cell-item
                  title="设备类型:"
                  :border-bottom="false"
                  :value="
                    !pmsWoDetailed[0].equTypeName
                      ? '请选择'
                      : pmsWoDetailed[0].equTypeName
                  "
                  @click="
                    getEquTypeByStationId();
                    selece_type = 'equTypeName';
                    label_name = 'equtypename';
                    value_name = 'idK';
                  "
                ></u-cell-item>
              </u-form-item>
              <u-form-item>
                <u-cell-item
                  title="设备:"
                  :border-bottom="false"
                  :value="
                    pmsWoDetailed[0].equName
                      ? pmsWoDetailed[0].equName
                      : '请选择'
                  "
                  @click="
                    selece_type = 'equName';
                    getEquList();
                    deviceName = pmsWoDetailed[0].equName;
                  "
                ></u-cell-item>
              </u-form-item>

              <u-form-item>
                <u-cell-item
                  title="计划开始时间:"
                  :border-bottom="false"
                  :value="
                    listOrderData.startTime == ''
                      ? '请选择'
                      : listOrderData.startTime
                  "
                  @click="
                    show_date = true;
                    date_type = 'startTime';
                  "
                  :arrow="false"
                >
                  <u-icon slot="right-icon" name="calendar"></u-icon>
                </u-cell-item>
              </u-form-item>
              <u-form-item>
                <u-cell-item
                  title="计划结束时间:"
                  :border-bottom="false"
                  :value="
                    listOrderData.endTime == ''
                      ? '请选择'
                      : listOrderData.endTime
                  "
                  @click="
                    show_date = true;
                    date_type = 'endTime';
                  "
                  :arrow="false"
                >
                  <u-icon slot="right-icon" name="calendar"></u-icon>
                </u-cell-item>
              </u-form-item>
            </u-form>
          </view>
        </scroll-view>
        <view class="footer">
          <u-button
            :custom-style="customStyle"
            type="primary"
            size="medium"
            :ripple="true"
            @click="crearedOrder"
            >创建</u-button
          >
        </view>
      </view>
    </view>

    <u-select
      v-model="show_picker"
      :list="columns"
      :label-name="label_name"
      :value-name="value_name"
      @confirm="onConfirm"
      @cancel="onCancel"
    ></u-select>
    <u-picker
      v-model="show_date"
      mode="time"
      :params="params"
      @confirm="setDate"
      @cancel="onCancel"
    ></u-picker>
    <SelectArea
      v-if="show_Area"
      :constructAreaName="listOrderData.constructArea"
      :constructArea="workArea"
      @close="show_Area = false"
      @setArea="setArea"
    ></SelectArea>
    <!-- 施工区域 -->
    <SelectPeople
      :keywordsFilter="true"
      :radio="true"
      v-if="show_people"
      :peopleName="listOrderData.woLeaderName"
      :people="leaderOptions"
      @close="show_people = false"
      @setPeople="setPeople"
    ></SelectPeople>
    <!-- 选择机构 -->
    <ljs-treeChoose
      :keywordsFilter="true"
      :data="departList"
      @getChooseValue="orgchange"
      @close="orgcancle"
      v-if="orgShow"
    />

    <!-- 设备类型选择 -->
    <ljs-treeChoose
      :keywordsFilter="true"
      :data="equDataList"
      @getChooseValue="equTypeChange"
      @close="equTypeCnacle"
      v-if="equTypeShow"
    />
    <!-- 选择设备 -->

    <selectDevice
      v-show="show_device"
      :deviceName="deviceName"
      :device="optionEquOption"
      @close="show_device = false"
      @setDevice="setDevice"
    ></selectDevice>
    <SelectStation
      :keywordsFilter="true"
      :radio="true"
      v-if="show_station"
      :stationName="listOrderData.locationName"
      :station="station_options"
      @close="show_station = false"
      @setStation="setStation"
    ></SelectStation>
  </view>
</template>

<script>
import { PMS_DICT_CONTROLLER, WORK_CONTROLLER } from "../../api/pms";
import { DICCONTROLLER } from "../../api/sys";
import SelectArea from "../../components/myWork/viewWork/selectArea.vue";
import selectDevice from "../../components/myWork/viewWork/selectDevice.vue";
import SelectPeople from "../../components/myWork/viewWork/selectPeople.vue";
import SelectStation from "../../components/myWork/viewWork/selectStation";
import { mapState } from "vuex";
import { transformData } from "@/utils/utils.js";
import { EQUCONTROLLER } from "../../api/eqt.js";
export default {
  components: {
    SelectArea,
    selectDevice,
    SelectPeople,
    SelectStation,
  },
  props: {},
  data() {
    return {
      equTypeShow: false,
      equDataList: [],
      value: 20,
      departList: [],
      orgShow: false,
      station_options: [],
      people_options: [],
      customStyle: {
        // backgroundColor: "#15c6ac",
        width: "40%",
      },
      listOrderData: {
        woCategory: "",
      },
      columns: [],
      type: true,
      show_picker: false,
      show_date: false,
      label_name: "",
      value_name: "",
      selece_type: "", // 下拉框类型
      show_station: false,
      show_people: false,
      show_Area: false,
      show_device: false,
      teamName_select: false, // 显示班组级联框
      leaderOptions: [], //工单人员列表
      taskOptions: [],
      optionEquOption: [],
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: true,
      },
      pmsWoDetailed: [
        {
          taskType: "",
          taskYearName: "",
          taskName: "",
          equID: "",
          equName: "",
          equTypeID: "",
          equTypeName: "",
          orderNumber: "",
          taskLocation: "",
          taskLocationName: "",
          endTime: "",
          startTime: "",
          detailedContent: "",
        },
      ], // 任务详情
      pmsWoTools: [], // 工器具
      remark: "", // 处理意见
      deviceName: "",
      contentStyle: {
        borderBottom: "1px solid red",
      },
      rules: {
        major: {
          required: true,
          message: "请选择专业",
          trigger: "change",
        },
        woLineName: {
          required: true,
          message: "请选择线路",
          trigger: "change",
        },
        managementOrgName: {
          required: true,
          message: "请选择机构",
          trigger: "change",
        },
        locationName: {
          required: true,
          message: "请选择所在地点",
          trigger: "change",
        },
        woLeaderName: {
          required: true,
          message: "请选择执行人",
          trigger: "change",
        },
        taskName: {
          required: true,
          message: "请选择作业任务",
          trigger: "change",
        },
      },
    };
  },
  computed: {
    ...mapState([
      "userInfo",
      "workOrderType",
      "workProfession",
      "workOrderState",
      "lineTree",
      "reeByOrgnum",
      "workArea",
    ]),
  },
  watch: {},
  onReady() {
    this.$refs.uform.setRules(this.rules);
  },
  onShow() {},
  async onLoad(options) {
    this.typeid = options.typeid;
  },
  async created() {
    this.listOrderData.managementOrgName = this.userInfo?.org?.name;
    this.listOrderData.managementOrg = this.userInfo?.org?.name;
    this.listOrderData.major = this.userInfo?.roles[0].major;
    this.listOrderData.woCategory = "临时工单";
    this.listOrderData.managementOrg = this.userInfo?.org?.num;
    if (this.lineTree.length == 1) {
      console.log("this.lineTree", this.lineTree);
      this.listOrderData.woLineName = this.lineTree[0].name;
      this.listOrderData.woLine = this.lineTree[0].idK;
      this.handleLine();
    }
    this.getNameByOrgId();
    this.getDirct();
  },
  methods: {
    equTypeCnacle() {
      this.equTypeShow = false;
    },
    equTypeChange(val, cc) {
      console.log(val);
      console.log(cc);
      let item = cc[cc.length - 1];
      if (!item.leaf) {
        uni.showToast({
          title: "请选择叶子节点",
          icon: "none",
        });
      } else {
        this.pmsWoDetailed[0].equTypeName = item.label;
        this.pmsWoDetailed[0].equTypeID = item.id;
        this.equTypeShow = false;
      }
    },
    // 选择地点
    setStation(obj) {
      if (obj.name.toString() == this.listOrderData.locationName) return;
      this.listOrderData.locationName = obj.name.toString();
      this.listOrderData.location = obj.id.toString();
      this.pmsWoDetailed[0].equTypeName = "";
      this.pmsWoDetailed[0].equTypeID = "";
      this.pmsWoDetailed[0].equName = "";
      this.pmsWoDetailed[0].equID = "";
      this.show_station = false;
    },
    //  选择人员
    setPeople(obj) {
      this.listOrderData.woLeaderName = obj.name.toString();
      this.listOrderData.woLeader = obj.id.toString();
      this.show_people = false;
    },
    /**
     * 根据选择的设备类型获取 设备列表
     */
    async getEquList() {
      let equTypeID = this.pmsWoDetailed[0].equTypeID;
      if (!equTypeID) {
        uni.showToast({
          title: "请先选择设备类型",
          icon: "none",
        });
        return;
      }
      let code = this.station_options.filter(
        (i) => i.id == this.listOrderData.location
      )[0]?.code;

      this.fetch(
        "post",
        this.$store.state.baseUrl + WORK_CONTROLLER.POST_EQU_EQULIST,
        {
          equtype: this.pmsWoDetailed[0].equTypeID,
          station: code,
          page: 1,
          size: 9999999,
        },
        false
      ).then((res) => {
        if (res?.data) {
          this.show_device = true;
          this.optionEquOption = res?.data?.content;
          this.optionEquOption = this.reduceArray(this.optionEquOption, "idk");
        }
      });
    },
    // 数组对象元素去重
    reduceArray(initialArr, attr) {
      // const uniqueArr = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
      let uniqueArr = initialArr.reduce((acc, obj) => {
        let existingObj = acc.find((item) => item[attr] === obj[attr]);
        if (!existingObj) {
          acc.push(obj);
        }
        return acc;
      }, []);
      return uniqueArr;
    },
    // 设置 设备
    setDevice(obj) {
      this.pmsWoDetailed[0].equName = obj.name.toString();
      this.pmsWoDetailed[0].equID = obj.id.toString();
      this.show_device = false;
    },
    //  根据地点（车站）获取改地点下面的设备类型分类
    getEquTypeByStationId(param) {
      let locat = this.listOrderData.locationName;
      if (!locat) {
        uni.showToast({
          title: "请先选择所在地点",
          icon: "none",
        });
        return;
      }
      this.equDataList = [];
      this.fetch(
        "GET",
        this.$store.state.baseUrl + EQUCONTROLLER.GET_EQU_TYPE_BY_STATIONID,
        {
          stationId: this.listOrderData.location,
          useTree: 1,
        },
        false
      ).then((res) => {
        if (res.returnCode == 2004) {
          this.equDataList = transformData(res?.data);
          this.equTypeShow = true;
        } else {
          this.equDataList = [];
          this.equTypeShow = true;
        }
      });
    },
    async getDirct() {
      const res = await this.fetch(
        "post",
        this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE,
        {
          dicClass: "temp_task_type", // 获取作业任务数据字典
        },
        false
      );
      this.taskOptions = res.data;
    },
    returChName(value, options) {
      let name;
      let filterArr = options.filter((item) => item.code == value);
      filterArr.length ? (name = filterArr[0].value) : (name = value);
      // options.filter(item=>item.code==value)[0].value

      return name;
    },
    formatDate(time) {
      var date = new Date(time);
      var year = date.getFullYear(),
        month = date.getMonth() + 1, //月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
      var newTime =
        year +
        "-" +
        (month < 10 ? "0" + month : month) +
        "-" +
        (day < 10 ? "0" + day : day) +
        " " +
        (hour < 10 ? "0" + hour : hour) +
        ":" +
        (min < 10 ? "0" + min : min) +
        ":" +
        (sec < 10 ? "0" + sec : sec);

      return newTime;
    },
    //  创建工单
    async crearedOrder() {
      this.$refs.uform.validate((valid) => {
        console.log("valid", valid);
        if (valid) {
          this.newSave();
        } else {
        }
      });
    },
    //  获取机构下面的人员
    getNameByOrgId() {
      if (this.listOrderData.managementOrg) {
        this.fetch(
          "get",
          this.$store.state.baseUrl + WORK_CONTROLLER.GET_NAME_BY_ORGID,
          {
            num: this.listOrderData.managementOrg,
          }
        ).then((res) => {
          if (res?.success) {
            this.leaderOptions = res?.data;
          }
        });
      } else {
        this.leaderOptions = [];
      }
    },
    showORG() {
      let self = this;
      this.orgShow = true;
      self.departList = self.reeByOrgnum.map((org) => self.mapTree(org));
      console.log(self.departList);
    },
    mapTree(org) {
      const haveChildren =
        Array.isArray(org.children) && org.children.length > 0;
      return {
        id: org.orgnum,
        label: org.text,
        openTag: false,
        choose: false,
        children: haveChildren ? org.children.map((i) => this.mapTree(i)) : [],
      };
    },
    orgchange(org, items) {
      this.listOrderData.managementOrgName = items[items.length - 1].label;
      this.listOrderData.managementOrg = items[items.length - 1].id;
      setTimeout(() => {
        this.orgcancle();
      }, 500);
      this.getNameByOrgId();
      this.listOrderData.woLeaderName = "";
      this.listOrderData.woLeader = "";
    },
    orgcancle() {
      this.orgShow = false;
    },

    //  设置选择的施工区域
    setArea(obj) {
      this.listOrderData.constructArea = obj.name.toString();
      // this.listOrderData.constructPerson = obj.id;
      this.show_Area = false;
    },

    checkWoRequire() {
      if (
        !this.listOrderData.major ||
        !this.listOrderData.woLineName ||
        !this.listOrderData.managementOrgName ||
        !this.listOrderData.locationName ||
        !this.listOrderData.woCategory ||
        !this.listOrderData.woLeaderName ||
        !this.pmsWoDetailed[0].taskName
      ) {
        uni.showToast({
          title: "请填写必填项",
          icon: "none",
        });
        return false;
      } else {
        return true;
      }
    },
    async newSave() {
      if (
        new Date(this.listOrderData.startTime).getTime() >
        new Date(this.listOrderData.endTime).getTime()
      ) {
        uni.showToast({
          title: "开始时间不能大于结束时间",
          icon: "none",
        });
        return;
      }
      let param = {
        pmsWoDetailedWorkDOList: this.pmsWoDetailed,
        pmsWoToolsDOList: this.pmsWoTools,
        pmsWoinforDOList: this.listOrderData,
      };
      await this.fetch(
        "post",
        this.$store.state.baseUrl + WORK_CONTROLLER.POST_SAVE_PmsInfo,
        param
      ).then((res) => {
        if (res.success) {
          uni.showToast({
            title: "保存成功",
            icon: "none",
          });
          this.back();
        } else {
          uni.showToast({
            title: "保存失败",
            icon: "none",
          });
        }
      });
    },

    onConfirm(item) {
      switch (this.selece_type) {
        case "line":
          this.listOrderData.woLineName = item[0].label;
          this.listOrderData.woLine = item[0].value;
          this.handleLine(item); // 根据 地铁线路获取对应的站
          this.listOrderData.locationName = "";
          this.listOrderData.location = "";
          break;
        case "major":
          // this.listOrderData.major = item[0].label
          this.listOrderData.major = item[0].value;
          // this.listOrderData.professionCode = item[0].value
          break;
        case "constrareaName":
          this.listOrderData.constructArea = item[0].label;
          // this.listOrderData.constrareaCode = item[0].value
          break;
        case "leader":
          this.listOrderData.woLeaderName = item[0].label;
          this.listOrderData.woLeader = item[0].value;
          break;
        case "station":
          if (item[0].label == this.listOrderData.locationName) return;
          this.listOrderData.locationName = item[0].label;
          this.listOrderData.location = item[0].value;
          this.pmsWoDetailed[0].equTypeName = "";
          this.pmsWoDetailed[0].equTypeID = "";
          this.pmsWoDetailed[0].equName = "";
          this.pmsWoDetailed[0].equID = "";
          break;
        case "taskName":
          this.pmsWoDetailed[0].taskName = item[0].label;
          this.pmsWoDetailed[0].taskYearName = item[0].label;
          this.listOrderData.taskName = item[0].label;
          break;
        // case 'equTypeName':
        // 	this.pmsWoDetailed[0].equTypeName = item[0].label;
        // 	this.pmsWoDetailed[0].equTypeID = item[0].value;

        // 	break;
        default:
      }
      this.onCancel();
    },
    onCancel() {
      this.show_picker = false;
      this.show_date = false;
      this.show_station = false;
    },
    handleLine(obj) {
      if (this.listOrderData.woLine) {
        this.fetch(
          "get",
          this.$store.state.baseUrl + PMS_DICT_CONTROLLER.GET_NAME_BY_LINEID,
          {
            lineId: obj ? obj[0].value : this.listOrderData.woLine,
            orgNum: this.listOrderData.managementOrg,
          }
        ).then((res) => {
          if (res?.success) {
            this.station_options = res?.data;
          }
        });
      } else {
        this.station_options = [];
      }
    },
    setDate(obj) {
      let str = `${obj.year}-${obj.month}-${obj.day} ${obj.hour}:${obj.minute}:${obj.second}`;
      this.listOrderData[this.date_type] = str;
      this.onCancel();
    },
    back() {
      uni.navigateTo({
        url: `/pages/index/index`,
      });
    },
  },
};
</script>

<style scoped lang="less">
.u-form-item {
  flex: 1;
  padding: 0 5px;
}

/deep/.htz-image-upload-Item {
  width: 70px;
  height: 70px;
}

.tips {
  color: red;
  font-size: 12px;
  padding: 5px 10px;
  border-bottom: 1px solid #f0f0f0;
}

/deep/.u-model__footer {
  border-top: 1px solid #f0f0f0;
}

.u-radio-group {
  padding: 10px 8px 0;
}

.rowClass {
  display: flex;
  flex-direction: row;

  &:nth-child(2) {
    // padding-left: 5px!important;
  }
}

.lastField::after {
  border-bottom: 0px;
}

/deep/ .u-cell {
  padding: 10px 2px !important;
}

.u-field {
  padding: 10px 2px 10px 8px !important;
}

/deep/.u-label {
  flex: 0 0 auto !important;
}

/deep/.u-cell--required:before {
  left: 2px;
}

/deep/.u-cell_title {
  color: #333;
  padding-left: 8px;
}

/deep/.u-cell__value {
  padding: 0 4px 0 8px;
}

.content {
  height: 100vh;
  width: 100%;
  // display: flex;
  // flex-direction: column;
  padding: 0 0rpx;
  overflow: hidden;
  // position: absolute;
}

.emergency_box {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.body_box {
  width: 95%;
  margin: 0 auto;
  background: #ffffff;
  position: relative;
  z-index: 100;
  height: calc(100vh - 100px);
  top: -100px;
  border-radius: 10px;
  padding: 10px 0;
}

.body_box_content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.scroll-Y {
  flex: 1;
  height: 0;
  padding: 0 20rpx;
}

.emergency_body_box {
  width: 100%;
  margin: 0 auto;
  height: calc(100% - 70px);
  // .body_box_content{
  // 	padding: 0 20rpx;
  // }
}

.footer {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  flex-wrap: wrap;
  // margin-top: 10rpx;
  border-radius: 0, 0, 10px, 10px;
  border-top: 1px solid #f1f1f1;
  padding: 10px 20rpx 10px;
  box-shadow: 5px -1px 5px #f6f6f6;

  /deep/.u-btn {
    // margin: 10rpx 5%;
    // margin-right: 30rpx;
    width: 30% !important;
  }

  :last-child {
    // margin-right: 0px;
  }
}

.app-title {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 99;
}

.list-area {
  hr {
    border: 0;
    border-top: 1px solid #f2f3f6;
  }

  .list-item-title {
    background-color: #f5f5f5;
    height: 70rpx;
    line-height: 70rpx;
    padding-left: 30rpx;
    font-size: 30rpx;
    color: #a7a7a7;
    font-weight: bold;
  }
}

:deep(.uni-input-input) {
  text-align: right;
}

/deep/.u-input__input {
  height: 100%;
}

.tools {
  color: #2979ff;

  text:nth-of-type(1) {
    padding-right: 6px;
  }

  text:nth-of-type(2) {
    padding-left: 0px;
  }
}

.wrap {
  padding: 30rpx;
}

.badge-button {
  padding: 4rpx 6rpx;
  background-color: #e4393c;
  color: #fff;
  border-radius: 10rpx;
  font-size: 22rpx;
  line-height: 1;
}

.complete {
  > view:nth-of-type(1) {
    padding: 26rpx 32rpx 26rpx 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;

    :nth-child(2) {
      // flex: 1;
      width: 60%;
    }
  }
}
</style>